package com.usian.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.concurrent.locks.Lock;

@RestController
public class OrderController {

    @Autowired
    private RedissonClient redissonClient;


    private static final HashMap<String,Integer> db = new HashMap();
    static {
        db.put("1",10);
    }

    @RequestMapping("list")
    public String list(){
        db.put("1",10);
        return "重置库存";
    }


    @RequestMapping("createOrder")
    public String createOrder(String username,String goodId){
        RLock lock = redissonClient.getLock(goodId);
        Integer num =null;
        try {
            lock.lock();
            num = db.get(goodId);
            if(num!=null && num>0){

                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //下单
                db.put(goodId,--num);
                System.out.println("username："+username+"下订单成功...剩余库存数量为："+num);
            }
            return "售罄";
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
         return "";
    }

    @RequestMapping("/get")
    public String get(String key, HttpSession httpSession){
        String valueStr = (String)httpSession.getAttribute(key);
        return valueStr;
    }
}
